package io.qifan.desktop.client.socket;


import io.qifan.desktop.api.protocol.BaseMessage;
import io.qifan.desktop.api.protocol.request.BaseRequest;
import io.qifan.desktop.api.protocol.response.BaseResponse;
import org.springframework.stereotype.Component;

import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.TimeoutException;

@Component
public class AsyncWriter<Q extends BaseRequest, R extends BaseResponse> {
    private final ConcurrentHashMap<String, AsyncResult<R>> resultMap = new ConcurrentHashMap<>();

    public R writeAndGet(Q message) {
        CompleteResult<R> completeResult = new CompleteResult<>();
        resultMap.put(message.getUuid(), completeResult);
        R result = null;
        try {
            result = completeResult.getResult();
        } catch (TimeoutException | InterruptedException e) {
            resultMap.remove(message.getUuid());
            throw new RuntimeException(e);
        }
        resultMap.remove(message.getUuid());
        return result;
    }

    public void complete(R message) {
        resultMap.get(message.getUuid()).complete(message);
    }
}
